package com.ace.lab.mobile.controller.users;

import com.ace.lab.base.model.Result;
import com.ace.lab.base.util.ResultBuilder;
import com.ace.lab.users.dto.UserQueryRequestProto;
import com.ace.lab.users.dto.UserQueryResponseProto;
import com.ace.lab.users.service.UserServiceGrpc;
import io.grpc.stub.StreamObserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.concurrent.CompletableFuture;

/**
 * Created by ace on 2017/7/6.
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceGrpc.UserServiceStub userServiceStub;

    @PostMapping("/login")
    public DeferredResult<Result> login(String userName, String password) {
        DeferredResult<Result> deferredResult = new DeferredResult<>();
        UserQueryRequestProto.UserQueryRequest request = UserQueryRequestProto.UserQueryRequest
                .newBuilder()
                .setUserName(userName)
                .build();
        CompletableFuture<UserQueryResponseProto.UserQueryResponse> future = new CompletableFuture<>();
        userServiceStub.queryByUserName(request, new StreamObserver<UserQueryResponseProto.UserQueryResponse>() {
            @Override
            public void onNext(UserQueryResponseProto.UserQueryResponse value) {
                future.complete(value);
            }

            @Override
            public void onError(Throwable t) {
                t.printStackTrace();
            }

            @Override
            public void onCompleted() {
                System.out.println("completed");
            }
        });
        future.whenComplete((res, ex) -> {
            if (ex == null) {
                deferredResult.setResult(new ResultBuilder().data(res).build());
            } else {
                deferredResult.setResult(new ResultBuilder().code("1002").msg(ex.getMessage()).build());
            }
        });
        return deferredResult;
    }

}
